package com.cloudcode.common.api;

import com.alibaba.fastjson.annotation.JSONField;
import com.cloudcode.common.utils.DateUtils;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serial;
import java.io.Serializable;
import java.util.Date;

/**
 * @author yunst
 * @Description 响应数据
 * @Date 2020/7/8 21:48
 */
@Data
@Builder
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class ApiResult<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = -4973947898768751875L;
    /**
     * 响应码
     */
    private int code;

    /**
     * 是否成功
     */
    private boolean success;

    /**
     * 响应消息
     */
    private String message;

    /**
     * 响应数据
     */
    private T data;
    /**
     * 响应时间
     */
    @JSONField(format = DateUtils.DATE_TIME_PATTERN)
    @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN)
    private Date time;

    public static ApiResult success() {
        return success(ApiCode.SUCCESS);
    }

    public static ApiResult ok() {
        return success(ApiCode.SUCCESS);
    }

    public static ApiResult success(ApiCode resultCode) {
        return ApiResult.builder().message(resultCode.getMessage())
                .code(resultCode.getCode())
                .time(new Date())
                .success(true).build();
    }

    public static <T> ApiResult<T> success(T data) {
        return success(ApiCode.SUCCESS, data);
    }

    public static <T> ApiResult<T> success(ApiCode resultCode, T data) {
        return (ApiResult<T>) ApiResult.builder().message(resultCode.getMessage())
                .code(ApiCode.SUCCESS.getCode())
                .data(data)
                .time(new Date())
                .success(true).build();
    }

    public static <T> ApiResult<T> success(int status, T data) {
        return (ApiResult<T>) ApiResult.builder().message(null)
                .code(status)
                .data(data)
                .time(new Date())
                .success(true).build();
    }

    public static ApiResult fail(int status) {
        return fail(status, ApiCode.FAIL.getMessage());
    }

    public static ApiResult fail() {
        return fail(ApiCode.SYSTEM_EXCEPTION);
    }

    public static ApiResult fail(ApiCode resultCode) {
        return ApiResult.builder().message(resultCode.getMessage())
                .code(resultCode.getCode())
                .time(new Date())
                .success(false).build();
    }

    public static ApiResult fail(int status, String message) {
        return ApiResult.builder().message(message)
                .code(status)
                .time(new Date())
                .success(false).build();
    }
}
